import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { CompanyService } from "src/modules/company/company.service";
import { dateNewFirst } from "src/utils/util";
import { Repository } from "typeorm";
import { Type } from "./type.entity";
import { CreateTypeDto } from "./dto/create-type.dto";
import { Company } from "src/modules/company/company.entity";

@Injectable()
export class TypeService {
  constructor(
    @InjectRepository(Type)
    private readonly typeRepository: Repository<Type>,
    private readonly companyService: CompanyService
  ) {}
  async findAll(): Promise<Type[]> {
    return (await this.typeRepository.find()).sort(dateNewFirst);
  }
  async findByCompany(companyId: string): Promise<Type[]> {
    const company = await this.companyService.find(companyId);
    return (
      await this.typeRepository.find({
        company,
      })
    ).sort(dateNewFirst);
  }
  find(id: string): Promise<Type> {
    return this.typeRepository.findOneOrFail(id, { relations: ["company"] });
  }
  findOneWithCompany(id: string): Promise<Type> {
    return this.find(id);
  }
  async create(
    createTypeDto: CreateTypeDto,
    company: string | Company
  ): Promise<Type> {
    const type = new Type();
    company =
      company instanceof Company
        ? company
        : await this.companyService.find(company);
    Object.assign(type, createTypeDto, { company });
    return this.typeRepository.save(type);
  }
  async remove(type: string | Type): Promise<Type> {
    const id = type instanceof Type ? type.id : type;
    const typeToRemove = await this.find(id);
    return await this.typeRepository.remove(typeToRemove);
  }
}
